const { getAllArtTopic } = require("../../../utils/request");

Page({
  data: {
    ArtTopicBasicInfoList: [], // 话题列表
    selectedTopicOption: {}, // 选中的话题
    isLoading: false, // 是否正在加载
    hasApplied: false, // 是否已经应用选择
  },

  async onLoad() {
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on("sendDataToChild", (data) => {
      if (data.selectedTopicOption) {
        this.setData({
          selectedTopicOption: data.selectedTopicOption,
        });
      }
      console.log(
        "话题子页面接收到的数据:",
        this.data.selectedTopicOption.id,
        "-",
        this.data.selectedTopicOption.topicName
      );
    });
    // 初始化加载数据
    await this.loadArtTopic();
  },

  // 加载所有话题数据（不分页查询）
  async loadArtTopic() {
    if (this.data.isLoading) {
      return; // 避免重复加载
    }

    this.setData({ isLoading: true });  // 设置加载状态

    try {
      wx.showLoading({ title: "Loading..." });
      const response = await getAllArtTopic({ fetchAll: true });

      if (response && response.data && response.data.length > 0) {
        // 按照 topicName 字母排序
        const sortedList = response.data.sort((a, b) => {
          const nameA = a.topicName.toUpperCase(); // 忽略大小写
          const nameB = b.topicName.toUpperCase(); // 忽略大小写
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0; // 两者相等
        });

        this.setData({
          ArtTopicBasicInfoList: sortedList,
        });
      } else {
        this.setData({ ArtTopicBasicInfoList: [] }); // 如果没有数据
      }
    } catch (error) {
      console.error("加载话题数据失败：", error);
      wx.showToast({
        title: "Failed to load data",
        icon: "none",
      });
    } finally {
      this.setData({ isLoading: false }); // 保证加载状态被清除
      wx.hideLoading();
    }
  },

  // 选择某个选项
  selectOption(e) {
    const { id, name } = e.currentTarget.dataset;
    this.setData({
      selectedTopicOption: {
        id: id,
        topicName: name,
      }
    });
    console.log("用户的选项：" + this.data.selectedTopicOption.id + " - " + this.data.selectedTopicOption.topicName);
  },

  // 应用选择
  applySelection() {
    if (this.data.hasApplied) return; // 如果已经发送过数据，直接返回
    const selectedTopicOption = this.data.selectedTopicOption;

    if (!selectedTopicOption || !selectedTopicOption.id) {
      wx.showModal({
        title: "Error",
        content: "Please select a topic before applying.",
        showCancel: false,
      });
      return;
    }

    // 获取事件通道并发送数据
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.emit("acceptDataFromChild", {
      selectedTopicOption,
    });

    this.setData({ hasApplied: true }); // 标记已发送
    wx.navigateBack(); // 返回上一页
  },

  // 页面卸载时，默认返回键也会触发
  onUnload() {
    if (this.data.hasApplied) return; // 如果已经发送过数据，跳过逻辑

    const selectedTopicOption = this.data.selectedTopicOption;
    if (selectedTopicOption && selectedTopicOption.id) {
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.emit("acceptDataFromChild", {
        selectedTopicOption,
      });
    }
  },
});
